package com.sto.stoapp.activity.sales;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.adapter.SelectOrderAdapter;
import com.sto.stoapp.broadcast.EixtToViewManager;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.OrderManager;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.response.download.info.OrderRecordInfo;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.listener.StoOnItemClickListener;
import com.sto.stoapp.listener.StoOnItemSelectedListener;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public class SalesOrderViewActivity extends BaseActivity {

	private Button backBtn;
	private Button operBtn;
	private Button downBtn;
	protected static final int LIST_FRESH_RESULT = 0x43;

	private ListView order_list;

	private TextView order_detail;

	private SelectOrderAdapter orderAdapter;

	private List<OrderRecordInfo> courierDatas = new ArrayList<OrderRecordInfo>();

	private int SelectOderIndex = -1;

	private BufferThread bufferThread;

	private RefreshBroad refreshBroad;
	// private EixtToOrderViewBroad orderViewBroad;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == LIST_FRESH_RESULT) {
				if (courierDatas.size() > 0) {
					courierDatas.clear();
					if (orderAdapter != null) {
						orderAdapter.notifyDataSetChanged();
					}
					bufferThread = new BufferThread(SalesOrderViewActivity.this);
					bufferThread.start();
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_order_view);
		this.setStoTitle(R.string.order_piece_view);
		initWidget();
		initListener();
		// register();
		bufferThread = new BufferThread(this);
		bufferThread.start();
	}

	/**
	 * 注册广播
	 * 
	 * @param action
	 *            事件
	 * 
	 *            public void register() { IntentFilter filter = new
	 *            IntentFilter(BusiExitAction.SALES_MAN_ORDER_BROAD);
	 *            orderViewBroad = new EixtToOrderViewBroad();
	 *            registerReceiver(orderViewBroad, filter); }
	 */

	private void initWidget() {

		backBtn = (Button) findViewById(R.id.return_back);
		operBtn = (Button) findViewById(R.id.order_operate);
		downBtn = (Button) findViewById(R.id.order_down);

		order_list = (ListView) findViewById(R.id.order_listview);
		order_detail = (TextView) findViewById(R.id.order_detailview);

	}

	private void initListener() {
		backBtn.setOnClickListener(new StoOnClickListener(this) {
			@Override
			public void mHonClick(View view) {
				finishEx();
			}
		});

		order_list.setOnItemClickListener(new StoOnItemClickListener(this) {
			@Override
			public void KcOnItemClickListener(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (courierDatas.size() > 0) {
					showOrderDetail(courierDatas.get(arg2));
					showDetailsDialog(courierDatas.get(arg2));
					order_list.setFocusable(true);
				}
			}
		});

		order_list
				.setOnItemSelectedListener(new StoOnItemSelectedListener(this) {
					@Override
					public void KcOnItemSelectedListener(AdapterView<?> arg0,
							View arg1, int arg2, long arg3) {
						if (courierDatas.size() > 0) {
							showOrderDetail(courierDatas.get(arg2));

							SelectOderIndex = arg2;
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}

				});

		order_list.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (!hasFocus) {
					SelectOderIndex = -1;
				}
			}
		});

		operBtn.setOnClickListener(new StoOnClickListener(this) {
			@Override
			public void mHonClick(View view) {
				/*
				 * Intent intent = new Intent(SalesOrderViewActivity.this,
				 * SalesOrderOperateActivity.class); intent.putExtra("order",
				 * "123232322232" + "|" + "1232323"); //
				 * intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				 * startActivity(intent);
				 */
				if (SelectOderIndex != -1 && courierDatas.size() > 0) {
					orderOperate(courierDatas.get(SelectOderIndex).oderNo,
							courierDatas.get(SelectOderIndex).empCode);
					order_list.setFocusable(true);
				} else {
					Helper.showSoundToast(SalesOrderViewActivity.this,
							"请选择一个订单编号", false);
				}
			}
		});

		downBtn.setOnClickListener(new StoOnClickListener(this) {
			@Override
			public void mHonClick(View view) {
				if (StoFilePreference.getInstance(SalesOrderViewActivity.this)
						.getOrderFunctionControl()) {
					Intent downIntent = new Intent(StoDownServer.UPDATE_ACTION);
					downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
							new int[] { MessageType.ORDER_DOWNLOAD_TYPE });
					sendBroadcast(downIntent);
					Helper.showToast(SalesOrderViewActivity.this,
							getString(R.string.upgrade_data_hint));
				} else {
					Helper.showToast(SalesOrderViewActivity.this,
							getText(R.string.order_function_no_open).toString());
				}
				finishEx();
			}
		});
	}

	private void showDetailsDialog(final OrderRecordInfo entity) {
		List<String> list = new ArrayList<String>();
		list.add("取件员：" + entity.empCode);
		list.add("取件网点：" + StoFilePreference.getInstance(this).getSiteCode());
		list.add("订单编号：" + entity.oderNo);
		list.add("下单时间：" + entity.oderTime);
		list.add("发件联系人：" + entity.contactName);
		list.add("发件联系电话：" + entity.contactPhone);
		list.add("发件客户地址：" + entity.contactAddress);
		list.add("发件联系手机：" + entity.contactMobilePhone);
		list.add("目的地：" + entity.desAreaCode);
		list.add("客户编号：" + entity.customerNo);
		list.add("发件客户：" + entity.customerName);
		list.add("客户备注：" + entity.customerRemark);

		String[] details = (String[]) list.toArray(new String[list.size()]);
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("订单详情").setNeutralButton("下一步", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				orderOperate(entity.oderNo, entity.empCode);
			}
		}).setItems(details, null);
		builder.create().show();
	}

	private void orderOperate(String orderCode, String pickupNetwork) {
		if (!OrderManager.getInstance(this).queryOrderIsProcess(orderCode)) {

			Intent intent = new Intent(this, SalesOrderOperateActivity.class);

			intent.putExtra("order", orderCode + "|" + pickupNetwork);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		} else {
			SendMsg();
			Helper.showSoundToast(this, "该订单已被处理,请重新选择!", false);
		}

	}

	/**
	 * 显示订单
	 * 
	 * @param entity
	 */
	private void showOrderDetail(OrderRecordInfo entity) {
		StringBuilder data = new StringBuilder();
		data.append(getString(R.string.order_details_date) + entity.oderTime
				+ "\n");
		data.append(getString(R.string.order_details_preson)
				+ entity.contactName + "\n");
		data.append(getString(R.string.order_details_phone)
				+ entity.contactMobilePhone + "\n");
		data.append(getString(R.string.order_details_tel) + entity.contactPhone
				+ "\n");

		data.append(getString(R.string.order_details_addr)
				+ entity.contactAddress + "\n");

		order_detail.setText(data.toString());
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		keyCode= StoApplication.getStoJni().getEventFuction(keyCode);
		switch (keyCode) {
		case StoPdaKeyEvent.KEYCODE_DEL:
			this.finish();
			break;
		case StoPdaKeyEvent.KEYCODE_MENU:
			if (StoFilePreference.getInstance(SalesOrderViewActivity.this)
					.getOrderFunctionControl()) {
				Intent downIntent = new Intent(StoDownServer.UPDATE_ACTION);
				downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
						new int[] { MessageType.ORDER_DOWNLOAD_TYPE });
				sendBroadcast(downIntent);
				Helper.showToast(SalesOrderViewActivity.this,
						getString(R.string.upgrade_data_hint));
			} else {
				Helper.showToast(SalesOrderViewActivity.this,
						getText(R.string.order_function_no_open).toString());
			}
			finishEx();
			break;
		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 查询数据缓冲线程
	 * 
	 * @author Administrator
	 * 
	 */
	class BufferThread extends BaseThread {
		private Context context;

		public BufferThread(Context context) {
			super(context);
			this.context = context;
		}

		@Override
		public void run() {
			OrderManager mgr = OrderManager.getInstance(context);
			courierDatas = mgr.queryAll();
			final int count = courierDatas == null ? 0 : courierDatas.size();

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (0 == count) {
						;
					} else {
						orderAdapter = new SelectOrderAdapter(context,
								courierDatas);
						order_list.setAdapter(orderAdapter);
						/*
						 * order_list.setFocusable(true);
						 * order_list.setFocusableInTouchMode(true);
						 */
						order_list.requestFocus();

					}
				}
			});
		}
	}

	private void SendMsg() {
		Message msg = handler.obtainMessage();
		msg.what = LIST_FRESH_RESULT;
		handler.sendMessage(msg);
	}

	private void finishEx() {
		SalesOrderViewActivity.this.finish();
	}

	@Override
	protected void onDestroy() {
		EixtToViewManager.getInstance().clearActivity();
		/*
		 * if(orderViewBroad != null){ unregisterReceiver(orderViewBroad); }
		 */
		if (refreshBroad != null) {
			unregisterReceiver(refreshBroad);
			refreshBroad = null;
		}
		courierDatas.clear();
		handler.removeMessages(LIST_FRESH_RESULT);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		SendMsg();
		if (refreshBroad == null) {
			refreshBroad = new RefreshBroad();
			IntentFilter filter = new IntentFilter(REFRESH_ORDER_ACTION);
			registerReceiver(refreshBroad, filter);
		}
		super.onResume();

	}

	class RefreshBroad extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			if (arg1.getAction().equals(REFRESH_ORDER_ACTION)) {
				SendMsg();
			}
		}
	}

}
